<template>
  <div class="all" v-if="curData">
    <!-- 指标/形态提醒 -->
    <scroller class="scroller" ref="scroller" resize="none">

      <div class="wrapper" v-if="dataList && dataList.length > 0">
        <!-- 标的 -->
        <text class="font28 text3 mb20">{{T('标的')}}</text>
        <div class="search bg2 mb40" @click="searchClick">
          <LImage v-if="pageRef != 'edit'" class="search-image mr20" :src="Config.img('ic_ai_search.png')"></LImage>
          <text :class="['font30', pair.length > 0 ? 'text2' : 'text3']">{{ pair.length > 0 ? pair :T('请选择标的')}}</text>
        </div>
        <!-- 触发条件 -->
        <text class="font28 text3 mb20">{{T('触发条件')}}</text>
        <div class="row all">
          <!-- 名称 -->
          <VConditionCell class="all" v-if="conditionName" :title="conditionName.value" :type="conditionName.type"
            :values="conditionName.values" :isShowDp="pageRef == 'create'" @onConditionClick="onConditionClick" />
          <div class="width26" />
          <!-- 第一个条件 -->
          <VConditionCell class="all" v-if="conditionFirst" :title="conditionFirst.value" :type="conditionFirst.type"
            :values="conditionFirst.values" :isShowDp="pageRef != 'edit'" @onConditionClick="onConditionClick" />
        </div>
        <!-- 其他条件 -->
        <div v-for="(item, index) in otherConditionList" :key="index">
          <VConditionCell :title="item.value" :type="item.type" :values="item.values" :isShowDp="pageRef != 'edit'"
            @onConditionClick="onConditionClick" />
        </div>
        <!-- 图片 -->
        <LImage class="center-img mb40" :src="curData.imageUrl"></LImage>
        <!-- 预警频率 -->
        <text class="font28 text3 mb20">{{T('预警频率')}}</text>
        <VConditionCell :title="frequency.name" @onConditionClick="onConditionClick" type="yjFrequency" />
        <div class="height20" />
        <!-- 到期时间 -->
        <text class="font28 text3 mb20">{{T('到期时间')}}</text>

        <VConditionCell :title="expirationTime || T('请选择到期时间')"
          :isGrayText="expirationTime && expirationTime.length > 0" @onConditionClick="onConditionClick"
          type="pickerTime" />
        <div class="height20" />
        <!-- 预警方式 -->
        <text class="font28 text3 mb20">{{T('预警方式')}}</text>
        <VCheck class="mb40" :menus="alertTypes" :selTypes="selAlertTypes" @checkClick="onAlertTypeSel" />

      </div>
    </scroller>

    <div class="bottom" v-if="dataList && dataList.length > 0">
      <div class="but main1" @click="onSave">
        <text class="font36 text1">{{T('保存')}}</text>
      </div>
    </div>

    <x-pair type="pair" v-if="showPair" :show="showPair" @overlayClick="pairHide" @onPairClick="onPairSel" />

    <x-picker type="date" v-if="showPicker" :show="showPicker" :curDate="expirationTime || curDate"
      @overlayClick="timePickerHide" @timePickerResult="timePickerResult" />

  </div>
</template>

<style src="@/_css/style.css" ></style>
<style scoped>
  .scroller {
    display: flex;
    flex-direction: column;
    flex: 1;
  }
  .refresh {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    width: 750px;
    height: 80px;
  }
  .wrapper {
    margin-top: 30px;
    display: flex;
    flex-direction: column;
    padding: 0 30px;
  }
  .search {
    flex-direction: row;
    align-items: center;
    height: 81px;
    padding-left: 28px;
    padding-right: 30px;
    border-color: #252a4d;
    border-radius: 4px;
    border-width: 1px;
  }
  .search-image {
    width: 32px;
    height: 32px;
  }
  .center-img {
    width: 690px;
    height: 640px;
    margin-top: 10px;
  }
  .bottom {
    height: 140px;
    flex-direction: column;
    margin-bottom: 40px;
  }
  .but {
    align-items: center;
    justify-content: center;
    margin: 20px 30px;
    height: 88px;
    border-radius: 16px;
  }
</style>

<script>
  import XPicker from "@/aide/picker/index.vue";
  import XPair from "@/aide/pair/targetPair.vue";
  import VConditionCell from "@/aide/view/VConditionCell.vue";
  import VCheck from "@/aide/view/VCheck.vue";
  import dateUtils from "@/aide/picker/dateutils.js";
  import jconfig from "@/_js/config";
  import jbroadcast from "@/_js/broadcast";
  import jmodal from "@/_js/modal";
  import jdebug from "@/_js/debug";
  import jhttps from "@/_js/https";
  import jtime from "@/_js/time";
  import jnavigator from "@/_js/navigator";
  const clipboard = weex.requireModule("clipboard");
  const animation = weex.requireModule("animation"); //动画
  const domModule = weex.requireModule("dom");
  const stream = weex.requireModule("stream"); //网络请求
  const weexFunction = weex.requireModule("WeexFunction");
  import I18N from "@/_i18n/i18n";
  var T = I18N.t;

  export default {
    components: {
      VConditionCell,
      XPicker,
      VCheck,
      XPair,
    },

    data() {
      return {
        Config: jconfig,
        T: T,
        pageRef: "", //1.add 2.create 3.edit
        id: null,
        indicatorId: null,
        type: "",
        curData: {},
        //筛选的数据
        dataList: [],
        //标的
        pair: "BTCUSDT",
        showPair: false,
        //触发条件
        conditionName: null,
        conditionFirst: null,
        otherConditionList: [],
        //预警频率
        frequency: {},
        frequencyList: [
          {
            name: T("仅一次"),
            type: "once",
          },
          {
            name: T("每分钟一次"),
            type: "oncePerMinute",
          },
        ],
        //到期时间
        showPicker: false,
        curDate: null,
        expirationTime: null,
        //预警方式
        alertTypes: [
          {
            name: T("APP提醒"),
            type: "app",
          },
          {
            name: T("Telegram提醒"),
            type: "tg",
          },

          {
            name: T("电话提醒"),
            type: "phone",
          },
        ],
        selAlertTypes: [],
      };
    },

    created() {
      this.pageRef = jnavigator.getParam("pageRef");
      this.id = jnavigator.getParam("id");
      this.indicatorId = jnavigator.getParam("indicatorId");
      this.type = jnavigator.getParam("type");
      if (this.type == "kline") {
        weexFunction.setTitle(T("形态提醒"));
      } else {
        weexFunction.setTitle(T("指标提醒"));
      }
      let isIos = weex.config.env.platform.toUpperCase() != "ANDROID";
      if (!isIos) {
        this.alertTypes = [
          {
            name: T("Telegram提醒"),
            type: "tg",
          },
          {
            name: T("电话提醒"),
            type: "phone",
          },
        ];
      }
    },

    mounted() {
      this.frequency = this.frequencyList[0];
      this.curDate = this.getCurrentFormattedDate();
      this.httpLoadData();
    },

    methods: {
      /********************************** HTTPS*/
      httpLoadData() {
        if (this.pageRef == "add") {
          jmodal.showLoad();
          var param = {
            indicatorId: parseInt(this.indicatorId),
          };
          jhttps.post("indicator/getIndicatorInfoById", param, true, (data) => {
            jmodal.hideLoad();
            if (data.status == 200) {
              this.curData = data.data;
              if (this.curData) {
                this.dataList = [];
                this.dataList.push(this.curData);
                this.updateName(0, true);
              }
            } else {
              jmodal.toast(data.msg);
            }
          });
        } else if (this.pageRef == "edit") {
          jmodal.showLoad();
          var param = {
            indicatorId: parseInt(this.indicatorId),
          };
          jhttps.post("indicator/getIndicatorInfoById", param, true, (data) => {
            if (data.status == 200) {
              this.updateEditInfo(data.data);
            } else {
              jmodal.hideLoad();
              jmodal.toast(data.msg);
            }
          });
        } else if (this.pageRef == "create") {
          jmodal.showLoad();
          var param = {
            indicatorType: this.type,
          };
          jhttps.post("indicator/getIndicatorInfoList", param, true, (data) => {
            jmodal.hideLoad();
            if (data.status == 200) {
              this.dataList = data.data;
              if (this.dataList.length > 0) {
                this.curData = this.dataList[0];
                this.updateName(0, true);
              }
            } else {
              jmodal.toast(data.msg);
            }
          });
        } else {
          jmodal.toast(T("失败"));
          setTimeout(() => {
            jnavigator.back();
          }, 1000);
        }
      },
      //用户编辑信息
      updateEditInfo(editInfo) {
        var param = {
          id: parseInt(this.id),
        };
        jhttps.post("indicator/getUserIndicatorById", param, true, (data) => {
          jmodal.hideLoad();
          if (data.status == 200) {
            this.curData = editInfo;
            if (this.curData) {
              this.dataList = [];
              this.dataList.push(this.curData);
              this.updateName(0, true);
              ///赋值
              //标的
              let userInfo = data.data;
              this.pair = userInfo.pair || "";
              //触发条件
              if (
                userInfo.triggerCondition &&
                Object.keys(userInfo.triggerCondition).length > 0
              ) {
                for (let key in userInfo.triggerCondition) {
                  if (userInfo.triggerCondition.hasOwnProperty(key)) {
                    if (key == this.conditionFirst.type) {
                      this.conditionFirst.value = userInfo.triggerCondition[key];
                    } else {
                      for (let i = 0; i < this.otherConditionList.length; i++) {
                        let item = this.otherConditionList[i];
                        if (item.type == key) {
                          item.value = userInfo.triggerCondition[key];
                        }
                      }
                    }
                  }
                }
              }
              //预警频率
              if (userInfo.frequency) {
                this.frequency = this.frequencyList.find(
                  (item) => item.type == userInfo.frequency
                );
              }
              //到期时间
              if (userInfo.expirationTime) {
                this.expirationTime = jtime.getTime(
                  userInfo.expirationTime,
                  "y-M-d H:m:s"
                );
              }
              //预警方式
              this.selAlertTypes = [];
              if (userInfo.appNotification) {
                this.selAlertTypes.push(this.alertTypes[0].type);
              }
              if (userInfo.tgNotification) {
                this.selAlertTypes.push(this.alertTypes[1].type);
              }
              if (userInfo.phNotification) {
                this.selAlertTypes.push(this.alertTypes[2].type);
              }
            }
          } else {
            jmodal.toast(data.msg);
          }
        });
      },
      updateName(index, isFirst = false) {
        let data = this.dataList[index];
        if (this.curData.indicatorName == data.indicatorName && !isFirst) {
          return;
        }
        this.curData = data;
        this.otherConditionList = [];
        this.conditionName = null;
        this.conditionFirst = null;
        let names = [];
        for (let i = 0; i < this.dataList.length; i++) {
          let item = this.dataList[i];
          names.push(item.indicatorName);
        }
        this.conditionName = {
          type: "indicatorName",
          values: names,
          value: names[index],
        };
        // 遍历 triggerCondition
        if (
          this.curData.triggerCondition &&
          Object.keys(this.curData.triggerCondition).length > 0
        ) {
          let i = 0;
          for (let key in this.curData.triggerCondition) {
            if (this.curData.triggerCondition.hasOwnProperty(key)) {
              if (i == 0) {
                this.conditionFirst = {
                  type: key,
                  values: this.curData.triggerCondition[key],
                  value: this.curData.triggerCondition[key][0],
                };
              } else {
                this.otherConditionList.push({
                  type: key,
                  values: this.curData.triggerCondition[key],
                  value: this.curData.triggerCondition[key][0],
                });
              }
            }
            i++;
          }
        }
        jdebug.log("conditionFirst=" + JSON.stringify(this.conditionFirst));
      },
      /********************************** 点击*/
      //选择标的
      searchClick() {
        if (this.pageRef == "edit") {
          return;
        }
        this.showPair = true;
      },
      onPairSel(item) {
        this.pair = item.pair;
      },
      pairHide() {
        setTimeout(() => {
          this.showPair = false;
        }, 200);
      },
      //条件点击
      onConditionClick(data) {
        if (data.type == this.conditionName.type) {
          //切换名称
          if (data.values.length <= 1) {
            return;
          }
          jmodal.actionSheet(data.values, data.value, (value) => {
            let index = data.values.indexOf(value);
            this.updateName(index);
          });
        } else if (data.type == "yjFrequency") {
          //切换频率
          let names = [];
          for (let i = 0; i < this.frequencyList.length; i++) {
            let item = this.frequencyList[i];
            names.push(item.name);
          }
          jmodal.actionSheet(names, this.frequency.name, (value) => {
            let index = names.indexOf(value);
            this.frequency = this.frequencyList[index];
          });
        } else if (data.type == this.conditionFirst.type) {
          //切换第一个条件
          if (this.pageRef == "edit") {
            return;
          }
          jmodal.actionSheet(data.values, data.value, (value) => {
            this.conditionFirst.value = value;
          });
        } else if (data.type == "pickerTime") {
          //时间选择器
          this.showPicker = true;
        } else {
          //切换其他条件
          if (this.pageRef == "edit") {
            return;
          }
          jmodal.actionSheet(data.values, data.value, (value) => {
            for (let i = 0; i < this.otherConditionList.length; i++) {
              let item = this.otherConditionList[i];
              if (item.type == data.type) {
                item.value = value;
                break;
              }
            }
          });
        }
      },

      /********************************** 时间选择器*/
      //时间选择器隐藏
      timePickerHide() {
        setTimeout(() => {
          this.showPicker = false;
        }, 200);
      },
      //时间选择器结果
      timePickerResult(dateTime) {
        this.expirationTime = dateTime;
      },

      /********************************** 预警方式*/
      onAlertTypeSel(item) {
        let index = this.selAlertTypes.indexOf(item.type);
        if (index == -1) {
          this.selAlertTypes.push(item.type);
        } else {
          this.selAlertTypes.splice(index, 1);
        }
      },
      /********************************** 最终保存*/

      onSave() {
        // //触发条件
        if (this.pair.length <= 0) {
          jmodal.toast(T("请选择标的"));
          return;
        }
        if (!this.expirationTime || this.expirationTime.length <= 0) {
          jmodal.toast(T("请选择到期时间"));
          return;
        }
        jmodal.showLoad();
        const date = dateUtils.createDate(this.expirationTime);
        let param = {
          indicatorId: parseInt(this.curData.id),
          pair: this.pair,
          frequency: this.frequency.type,
          expirationTime: date.getTime(),
        };
        //触发条件
        let triggerCondition = {};
        if (this.conditionFirst) {
          triggerCondition[this.conditionFirst.type] = this.conditionFirst.value;
        }
        if (this.otherConditionList.length > 0) {
          for (let i = 0; i < this.otherConditionList.length; i++) {
            let item = this.otherConditionList[i];
            triggerCondition[item.type] = item.value;
          }
        }
        param.triggerCondition = JSON.stringify(triggerCondition);
        //预警方式
        if (this.selAlertTypes.includes("app")) {
          param.appNotification = true;
        } else {
          param.appNotification = false;
        }
        if (this.selAlertTypes.includes("tg")) {
          param.tgNotification = true;
        } else {
          param.tgNotification = false;
        }
        if (this.selAlertTypes.includes("phone")) {
          param.phNotification = true;
        } else {
          param.phNotification = false;
        }
        if (this.pageRef == "edit") {
          param.id = parseInt(this.id);
          jhttps.postX("indicator/updateUserIndicator", param, true, (data) => {
            jmodal.hideLoad();
            if (data.status == 200) {
              jmodal.toast(T("保存成功"));
              jbroadcast.send("IndicatorEdit");
              jnavigator.back();
            } else {
              jmodal.toast(data.msg);
            }
          });
        } else {
          jhttps.postX("indicator/createUserIndicator", param, true, (data) => {
            jmodal.hideLoad();
            if (data.status == 200) {
              jmodal.toast(T("保存成功"));
              jnavigator.back();
              jnavigator.open("", "aide/tipAll", { index: 2 });
            } else {
              jmodal.toast(data.msg);
            }
          });
        }
      },

      /******************************* 其他 */
      //获取当前时间
      //格式化为 YYYY-MM-DD HH:mm:ss
      getCurrentFormattedDate() {
        const now = new Date();
        const year = now.getFullYear(); // 获取年份
        const month = (now.getMonth() + 1).toString().padStart(2, "0"); // 获取月份（0-11），并补零
        const day = now.getDate().toString().padStart(2, "0"); // 获取日期，并补零
        const hours = now.getHours().toString().padStart(2, "0"); // 获取小时，并补零
        const minutes = now.getMinutes().toString().padStart(2, "0"); // 获取分钟，并补零
        const seconds = now.getSeconds().toString().padStart(2, "0"); // 获取秒数，并补零
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
    },
  };
</script>